package com.wjf.shortlink.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.UUID;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wjf.shortlink.admin.common.biz.user.UserContext;
import com.wjf.shortlink.admin.common.constant.RedisCacheConstant;
import com.wjf.shortlink.admin.common.convention.exception.ClientException;
import com.wjf.shortlink.admin.common.convention.exception.ServiceException;
import com.wjf.shortlink.admin.common.enums.UserErrorCodeEnum;
import com.wjf.shortlink.admin.dao.entity.UserDAO;
import com.wjf.shortlink.admin.dao.mapper.UserMapper;
import com.wjf.shortlink.admin.dto.req.UserLoginReqDTO;
import com.wjf.shortlink.admin.dto.req.UserRegisterReqDTO;
import com.wjf.shortlink.admin.dto.req.UserUpdateReqDTO;
import com.wjf.shortlink.admin.dto.resp.UserLoginRespDTO;
import com.wjf.shortlink.admin.dto.resp.UserRespDTO;
import com.wjf.shortlink.admin.service.GroupService;
import com.wjf.shortlink.admin.service.UserService;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import static com.wjf.shortlink.admin.common.enums.UserErrorCodeEnum.USER_NAME_EXIST;
import static com.wjf.shortlink.admin.common.enums.UserErrorCodeEnum.USER_SAVE_ERROR;


@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, UserDAO> implements UserService {

    // 用户存在与否的布隆过滤器
    private final RBloomFilter<String> userRegisterCachePenetrationBloomFilter;
    private final RedissonClient redissonClient;
    private final StringRedisTemplate stringRedisTemplate;
    private final GroupService groupService;


    // 根据用户名称查询用户信息
    @Override
    public UserRespDTO getUserByUsername(String username) {
        LambdaQueryWrapper<UserDAO> queryWrapper = Wrappers.lambdaQuery(UserDAO.class)
                .eq(UserDAO::getUsername, username);
        UserDAO userDAO = baseMapper.selectOne(queryWrapper);
        if (userDAO == null) {
            throw new ServiceException(UserErrorCodeEnum.USER_NULL);
        }
        UserRespDTO userRespDTO = new UserRespDTO();
        BeanUtils.copyProperties(userDAO, userRespDTO);
        return userRespDTO;
    }

    // 判断用户是否存在
    @Override
    public Boolean hasUsername(String username) {
        return userRegisterCachePenetrationBloomFilter.contains(username);
    }

    // 用户注册
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void register(UserRegisterReqDTO userRegisterReqDTO) {
        String username = userRegisterReqDTO.getUsername();
        if (!hasUsername(username)) {
            throw new ClientException(USER_NAME_EXIST);
        }
        RLock lock = redissonClient.getLock(RedisCacheConstant.LOCK_USER_REGISTER_KEY + username);
        if (!lock.tryLock()) {
            throw new ClientException(USER_NAME_EXIST);
        }
        try {
            int inserted = baseMapper.insert(BeanUtil.toBean(userRegisterReqDTO, UserDAO.class));
            if (inserted < 1) {
                throw new ClientException(USER_SAVE_ERROR);
            }
            groupService.saveGroup(username, "默认分组");
            userRegisterCachePenetrationBloomFilter.add(username);
        } catch (DuplicateKeyException e) {
            throw new ClientException(USER_NAME_EXIST);
        } finally {
            lock.unlock();
        }
    }

    // 修改用户
    @Override
    public void update(UserUpdateReqDTO userUpdateReqDTO) {
        if (!Objects.equals(userUpdateReqDTO.getUsername(), UserContext.getUserName())) {
            throw new ClientException("当前登录用户修改请求异常！");
        }
        LambdaUpdateWrapper<UserDAO> updateWrapper = Wrappers.lambdaUpdate(UserDAO.class)
                .eq(UserDAO::getUsername, userUpdateReqDTO.getUsername());
        baseMapper.update(BeanUtil.toBean(userUpdateReqDTO, UserDAO.class), updateWrapper);
    }

    @Override
    // 用户登录
    public UserLoginRespDTO login(UserLoginReqDTO userLoginReqDTO) {
        LambdaQueryWrapper<UserDAO> queryWrapper = Wrappers.lambdaQuery(UserDAO.class)
                .eq(UserDAO::getUsername, userLoginReqDTO.getUsername())
                .eq(UserDAO::getPassword, userLoginReqDTO.getPassword())
                .eq(UserDAO::getDelFlag, 0);
        UserDAO userDAO = baseMapper.selectOne(queryWrapper);
        if (userDAO == null) {
            throw new ClientException("用户不存在");
        }
        Map<Object, Object> hasLoginMap = stringRedisTemplate.opsForHash()
                .entries(RedisCacheConstant.USER_LOGIN_KEY + userLoginReqDTO.getUsername());
        if (CollUtil.isNotEmpty(hasLoginMap)) {
            stringRedisTemplate.expire(RedisCacheConstant.USER_LOGIN_KEY + userLoginReqDTO.getUsername(), 30L, TimeUnit.MINUTES);
            String token = hasLoginMap.keySet().stream()
                    .findFirst()
                    .map(Object::toString)
                    .orElseThrow(() -> new ClientException("用户登录错误"));
            return new UserLoginRespDTO(token);
        }
        // Hash Key: login_用户名
        // Value: Key: token Val: JSON 字符串（用户信息）
        String uuid = UUID.randomUUID().toString();
        stringRedisTemplate.opsForHash().put(RedisCacheConstant.USER_LOGIN_KEY + userLoginReqDTO.getUsername(),
                uuid, JSON.toJSONString(userDAO));
        stringRedisTemplate.expire(RedisCacheConstant.USER_LOGIN_KEY + userLoginReqDTO.getUsername(), 30L, TimeUnit.MINUTES);
        return new UserLoginRespDTO(uuid);
    }

    @Override
    // 检查用户是否登录
    public Boolean checkLogin(String username, String token) {
        return stringRedisTemplate.opsForHash().get(RedisCacheConstant.USER_LOGIN_KEY + username, token) != null;
    }

    @Override
    // 用户退出登录
    public void logout(String username, String token) {
        if (checkLogin(username, token)) {
            stringRedisTemplate.delete(RedisCacheConstant.USER_LOGIN_KEY + username);
            return;
        }
        throw new ClientException("用户Token不存在或未登录");
    }
}
